package io.kiki.stack.netty.channelManager;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
@Setter
@Getter
public class ChannelEventListener {

    private final ConcurrentHashMap<ChannelEventType, List<ChannelEventProcessor>> map = new ConcurrentHashMap<ChannelEventType, List<ChannelEventProcessor>>(3);

    public void add(ChannelEventType channelEventType, ChannelEventProcessor channelEventProcessor) {
        List<ChannelEventProcessor> list = this.map.get(channelEventType);
        if (list == null) {
            this.map.putIfAbsent(channelEventType, new CopyOnWriteArrayList<ChannelEventProcessor>());
            list = this.map.get(channelEventType);
        }
        list.add(channelEventProcessor);
    }

    public void onEvent(ChannelEventType channelEventType, Channel channel, String remoteAddress) {
        List<ChannelEventProcessor> list = this.map.get(channelEventType);
        if (list != null) {
            for (ChannelEventProcessor channelEventProcessor : list) {
                channelEventProcessor.onEvent(channel, remoteAddress);
            }
        }
    }


}
